package cn.com.tom.dao.impl;

import cn.com.tom.bean.Company;
import cn.com.tom.bean.Experience;
import cn.com.tom.bean.Project;
import cn.com.tom.dao.ExperienceDao;
import cn.com.tom.util.Dbs;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ExperienceDaoImpl extends BaseDaoImpl<Experience> implements ExperienceDao {
    private static String GET_SQL;
    private static String QUERY_SQL;
    private static RowMapper<Experience> ROW_MAPPER;

    static {
        QUERY_SQL = "SELECT t1.id, t1.job,t1.intro,t1.begin_day,t1.end_day," +
                "t2.id,t2.intro,t2.logo,t2.name,t2.website " +
                "FROM experience t1 LEFT JOIN company t2 " +
                "ON t1.company_id=t2.id ";
        GET_SQL = QUERY_SQL + " WHERE t1.id=?";
        ROW_MAPPER = new RowMapper<Experience>() {
            @Override
            public Experience mapRow(ResultSet resultSet, int i) throws SQLException {
                Experience experience = new Experience();
                experience.setId(Integer.valueOf(resultSet.getInt("t1.id")));
                experience.setBeginDay(resultSet.getDate("t1.begin_day"));
                experience.setEndDay(resultSet.getDate("t1.end_day"));
                experience.setIntro(resultSet.getString("t1.intro"));
                experience.setJob(resultSet.getString("t1.job"));

                Company company = new Company();
                company.setId(Integer.valueOf(resultSet.getInt("t2.id")));
                company.setName(resultSet.getString("t2.name"));
                company.setWebsite(resultSet.getString("t2.website"));
                company.setLogo(resultSet.getString("t2.logo"));
                company.setIntro(resultSet.getString("t2.intro"));
                experience.setCompany(company);

                return experience;
            }
        };
    }

    @Override
    public boolean save(Experience bean) {
        Integer id = bean.id;
        String sql = "";
        List<Object> args = new ArrayList<>();

        args.add(bean.getJob());
        args.add(bean.getIntro());
        args.add(bean.getBeginDay());
        args.add(bean.getEndDay());
        args.add(bean.getCompanyId());

        if (id == null || id < 1) {
            sql = "INSERT INTO experience(job,intro,begin_day,end_day,company_id) VALUES(?,?,?,?,?)";
        } else {
            sql = "UPDATE experience SET job=?,intro=?,begin_day=?,end_day=?,company_id=? WHERE id=?";
            args.add(id);
        }
        return Dbs.save(sql, args.toArray());
    }

    @Override
    public Experience get(Integer id) {
        return Dbs.queryForObject(GET_SQL, ROW_MAPPER, id);
    }

    @Override
    public List<Experience> list() {
        return Dbs.list(QUERY_SQL, ROW_MAPPER);
    }

}
